import axios from 'axios';
import { showToast } from 'vant';
import router from '@/router';
import type { LoginParams, RegisterParams, UserInfo, Course, Teacher } from './types';

const api = axios.create({
  baseURL: '/api',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          showToast('请先登录');
          router.push('/login');
          break;
        case 403:
          showToast('没有权限');
          break;
        case 404:
          showToast('请求的资源不存在');
          break;
        case 500:
          showToast('服务器错误');
          break;
        default:
          showToast('网络错误');
      }
    } else {
      showToast('网络连接失败');
    }
    return Promise.reject(error);
  }
);

export const userApi = {
  login: (data: LoginParams) => api.post<{data: UserInfo}>('/user/login', data),
  register: (data: RegisterParams) => api.post<{data: UserInfo}>('/user/register', data),
  getUserInfo: () => api.get<{data: UserInfo}>('/user/info'),
  updateUserInfo: (data: Partial<UserInfo>) => api.put<{data: UserInfo}>('/user/info', data)
};

export const courseApi = {
  getCourses: () => api.get<{data: Course[]}>('/courses'),
  getCourseById: (id: number) => api.get<{data: Course}>(`/courses/${id}`),
  searchCourses: (keyword: string) => api.get<{data: Course[]}>('/courses/search', {
    params: { q: keyword }
  }),
  toggleFavorite: (courseId: number) => api.post('/courses/favorite', { courseId })
};

export const teacherApi = {
  getTeachers: () => api.get<{data: Teacher[]}>('/teachers'),
  getTeacherById: (id: number) => api.get<{data: Teacher}>(`/teachers/${id}`),
  getTeacherCourses: (id: number) => api.get<{data: Course[]}>(`/teachers/${id}/courses`)
};
